package cn.tdzk;

import java.util.ArrayList;
import java.util.stream.Collectors;

import org.json.JSONArray;
import org.json.JSONObject;

public class DataConverter {
    public static double[] toDoubleArray(String value) {
        String[] split = value.split(",");
        int size = split.length;
        double[] result = new double[size];

        for (int i = 0; i < size; ++i) {
            String str = split[i];
            double data = Double.parseDouble(str);
            result[i] = data;
        }

        return result;
    }

    public static int[] toIntArray(String value) {
        String[] split = value.split(",");
        int size = split.length;
        int[] result = new int[size];

        for (int i = 0; i < size; ++i) {
            String str = split[i];
            int data = Integer.parseInt(str);
            result[i] = data;
        }

        return result;
    }

    public static ArrayList<Double> toDoubleList(String value) {
        String[] split = value.split(",");
        int size = split.length;
        ArrayList<Double> result = new ArrayList<>();

        for (int i = 0; i < size; ++i) {
            String str = split[i];
            Double data = Double.parseDouble(str);
            result.add(i, data);
        }

        return result;
    }

    public static ArrayList<Double> toDoubleList(JSONObject jsonObject, String key) {
        JSONArray data = jsonObject.getJSONArray(key);
        return data.toList().stream().map(x -> (Double) x).collect(Collectors.toCollection(ArrayList::new));
    }

    public static ArrayList<Integer> toIntegerList(String value) {
        String[] split = value.split(",");
        int size = split.length;
        ArrayList<Integer> result = new ArrayList<>();

        for (int i = 0; i < size; ++i) {
            String str = split[i];
            int data = Integer.parseInt(str);
            result.add(i, data);
        }

        return result;
    }

    public static ArrayList<Integer> toIntegerList(JSONObject jsonObject, String key) {
        JSONArray data = jsonObject.getJSONArray(key);
        return data.toList().stream().map(x -> (Integer) x).collect(Collectors.toCollection(ArrayList::new));
    }

    public static ArrayList<String> toStringList(JSONObject jsonObject, String key) {
        JSONArray data = jsonObject.getJSONArray(key);
        return data.toList().stream().map(x -> (String) x).collect(Collectors.toCollection(ArrayList::new));
    }
}
